import arcpy
import json
import os
def get_field_mapping(feature_class_path):
    """
    获取要素类的字段名称与别名映射字典
    :param feature_class_path: 要素类的完整路径（str）
    :return: 字段名与别名字典（dict）
    """
    fields = arcpy.ListFields(feature_class_path)
    return {field.name: field.aliasName for field in fields}
def write_json_file(data, output_path):
    """
    将字典数据写入JSON文件，自动创建输出目录
    :param data: 要写入的字典数据（dict）
    :param output_path: 输出文件完整路径（str）
    """
    os.makedirs(os.path.dirname(output_path), exist_ok=True)
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    arcpy.AddMessage(f"生成文件: {output_path}")
def process_feature_class(feature_class_path, output_dir):
    """
    处理单个要素类：获取字段映射并写入JSON文件
    :param feature_class_path: 要素类完整路径（str）
    :param output_dir: 输出目录路径（str）
    """
    try:
        # 获取要素类基础信息
        desc = arcpy.Describe(feature_class_path)
        fc_name = desc.name
        
        # 生成输出路径并处理字段映射
        output_path = os.path.join(output_dir, f"{fc_name}.json")
        field_mapping = get_field_mapping(feature_class_path)
        
        # 写入JSON文件
        write_json_file(field_mapping, output_path)
    except Exception as e:
        arcpy.AddError(f"处理要素类失败 [{fc_name}]: {str(e)}")
        raise
def process_workspace(gdb_path, output_root):
    """
    处理整个地理数据库工作空间
    :param gdb_path: GDB完整路径（str）
    :param output_root: 根输出目录（str）
    """
    arcpy.env.workspace = gdb_path
    
    # 处理根目录下的独立要素类
    standalone_fcs = arcpy.ListFeatureClasses()
    if standalone_fcs:
        for fc in standalone_fcs:
            fc_path = os.path.join(gdb_path, fc)
            process_feature_class(fc_path, output_root)
        arcpy.AddMessage(f"共处理独立要素类: {len(standalone_fcs)} 个")
    else:
        arcpy.AddMessage("GDB根目录下无独立要素类")
    
    # 处理要素数据集
    datasets = arcpy.ListDatasets("*", "Feature")
    if datasets:
        for dataset in datasets:
            dataset_name = os.path.basename(dataset)
            dataset_output_dir = os.path.join(output_root, dataset_name)
            
            # 处理数据集内要素类
            fcs_in_dataset = arcpy.ListFeatureClasses(feature_dataset=dataset)
            if fcs_in_dataset:
                for fc in fcs_in_dataset:
                    fc_path = os.path.join(gdb_path, dataset, fc)
                    process_feature_class(fc_path, dataset_output_dir)
                arcpy.AddMessage(f"数据集 [{dataset_name}] 处理完成，共 {len(fcs_in_dataset)} 个要素类")
            else:
                arcpy.AddWarning(f"要素数据集 [{dataset_name}] 为空")
    else:
        arcpy.AddMessage("GDB中未找到要素数据集")
def process_feature_dataset(feature_dataset_desc, output_root):
    """
    处理单个要素数据集
    :param feature_dataset_desc: 要素数据集Describe对象
    :param output_root: 根输出目录（str）
    """
    gdb_path = feature_dataset_desc.path
    dataset_name = feature_dataset_desc.name
    output_dir = os.path.join(output_root, dataset_name)
    
    # 处理数据集内要素类
    arcpy.env.workspace = gdb_path
    fcs = arcpy.ListFeatureClasses(feature_dataset=dataset_name)
    
    if fcs:
        for fc in fcs:
            fc_path = os.path.join(gdb_path, dataset_name, fc)
            process_feature_class(fc_path, output_dir)
        arcpy.AddMessage(f"要素数据集 [{dataset_name}] 处理完成，共 {len(fcs)} 个要素类")
    else:
        arcpy.AddWarning(f"要素数据集 [{dataset_name}] 内无要素类")
def export_fields(input_path, output_dir):
    """
    主处理函数：根据输入类型路由到不同处理方法
    :param input_path: 输入路径（GDB/要素数据集/要素类）
    :param output_dir: 输出目录路径
    """
    try:
        desc = arcpy.Describe(input_path)
        data_type = desc.dataType
        
        if data_type == "Workspace":
            process_workspace(input_path, output_dir)
        elif data_type == "FeatureDataset":
            process_feature_dataset(desc, output_dir)
        elif data_type == "FeatureClass":
            process_feature_class(input_path, output_dir)
        else:
            arcpy.AddError("输入必须是文件地理数据库(.gdb)、要素数据集或要素类")
    except Exception as e:
        arcpy.AddError(f"处理失败: {str(e)}")
        raise
if __name__ == "__main__":
    # ArcGIS工具参数获取
    input_path = arcpy.GetParameterAsText(0)
    output_dir = arcpy.GetParameterAsText(1)
    export_fields(input_path, output_dir)
